import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/login'
import Register from '@/views/register'
import goRent from '@/views/gorent'
import Layout from '@/views/layout'
import Index from '@/views/index'
import Findhouse from '@/views/findhouse'
import Message from '@/views/message'
import User from '@/views/user'
import myCollect from '@/views/mycollect'
import myRent from '@/views/myrent'
import mapFind from '@/views/mapFind'
import { getToken } from '@/utils/storage'
import cityList from '@/views/citylist'
Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    { path: '/mapFind', component: mapFind },
    { path: '/login', component: Login },
    { path: '/mycollect', component: myCollect },
    { path: '/myrent', component: myRent },
    { path: '/register', component: Register },
    { path: '/gorent', component: goRent },
    { path: '/citylist', component: cityList },
    {
      path: '/',
      component: Layout,
      redirect: '/index',
      children: [
        { path: '/index', component: Index },
        { path: '/findhouse', component: Findhouse },
        { path: '/message', component: Message },
        {path: '/user', component: User,}
      ]
    }
  ]
})
//全局前置守卫
const whiteList = ['/login', '/register','/user']
// to: 去哪里 from :从哪里来  next  是一个函数，调用表示放行
router.beforeEach((to, from, next) => {
  const token = getToken()
  if (token) {
    next() // 如果有携带token 直接放行
  } else {
    if (whiteList.includes(to.path)) {
      next() // 是否在白名单里面，在的话放行，不在的话跳转登录页面
    } else {
      next('/login')
    }
  }
})
export default router
